package com.sptokentest.satoken;

import cn.dev33.satoken.stp.StpInterface;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sptokentest.entity.Menu;
import com.sptokentest.entity.Role;
import com.sptokentest.entity.RoleMenu;
import com.sptokentest.entity.UserRole;
import com.sptokentest.service.MenuService;
import com.sptokentest.service.RoleMenuService;
import com.sptokentest.service.RoleService;
import com.sptokentest.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class StpInterfaceImpl implements StpInterface {

    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private RoleMenuService roleMenuService;
    @Autowired
    private MenuService menuService;

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        UserRole userRole = getUserRole(loginId);
        LambdaQueryWrapper<RoleMenu> lqw = new LambdaQueryWrapper<>();
        lqw.eq(RoleMenu::getRoleId,userRole.getRoleId());
        List<RoleMenu> roleMenuList = roleMenuService.list(lqw);
        List<Long> menuIds = new ArrayList<>();
        for (RoleMenu rolemenu :
                roleMenuList) {
            menuIds.add(rolemenu.getMenuId());
        }
        List<Menu> menus = menuService.listByIds(menuIds);
        List<String> perms = new ArrayList<>();
        for (Menu menu :
                menus) {
            perms.add(menu.getPerms());
        }
//        for (Long menuId:
//             menuIds) {
//            LambdaQueryWrapper<Menu> lqw2 = new LambdaQueryWrapper<>();
//            lqw2.eq(Menu::getMid,menuId);
//            for (Menu item :
//                    menuService.list(lqw2)) {
//                perms.add(item.getPerms());
//            }
//        }
        return perms;
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        UserRole userRole = getUserRole(loginId);
        LambdaQueryWrapper<Role> lqw1 = new LambdaQueryWrapper<>();
        lqw1.eq(Role::getRoleId,userRole.getRoleId()).eq(Role::getStatus,1);
        List<Role> roleList = roleService.list(lqw1);
        List<String> rolePerList = new ArrayList<>();
        for (Role role :
                roleList) {
            rolePerList.add(role.getPer());
        }
        return rolePerList;
    }

    private UserRole getUserRole(Object loginId){
        LambdaQueryWrapper<UserRole> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UserRole::getUserId,loginId);
        return userRoleService.getOne(lqw);
    }
}
